package com.wbt.bambootown.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.jaygoo.selector.MultiSelectPopWindow;
import com.wbt.bambootown.FrameApp;
import com.wbt.bambootown.R;
import com.wbt.bambootown.cons.Cons;
import com.wbt.bambootown.entity.Facility;
import com.wbt.bambootown.entity.CameraDevices;
import com.wbt.bambootown.entity.Farms;
import com.wbt.bambootown.hk.DeviceBean;
import com.wbt.bambootown.hk.HC_DVRManager;
import com.wbt.bambootown.mvp.contract.HomeContract;
import com.wbt.bambootown.mvp.frame.MvpFragment;
import com.wbt.bambootown.mvp.frame.base.BaseView;
import com.wbt.bambootown.mvp.presenter.HomePresenter;
import com.wbt.bambootown.ui.activity.CameraPicActivity;
import com.wbt.bambootown.ui.activity.FullScreenActivity;
import com.wbt.bambootown.ui.adapter.FacilityAdapter;
import com.wbt.bambootown.ui.adapter.FarmsAdapter;
import com.wbt.bambootown.ui.view.popwindow.CustomPopWindow;
import com.wbt.bambootown.utils.EventCenter;
import com.wbt.bambootown.utils.Log;
import com.wbt.bambootown.utils.SPUtils;
import com.wbt.bambootown.utils.VibrateHelp;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wufan on 2018/5/15.
 */

public class HomePageFragment extends MvpFragment<HomePresenter> implements
        HomeContract.View,
        FarmsAdapter.onItemClick,
        FacilityAdapter.onItemClick,
        CustomPopWindow.onDismissClick,
        View.OnTouchListener {

    @BindView(R.id.tv_farms)
    TextView mTvFarms;
    @BindView(R.id.iv_choose_farms)
    ImageView mIvChooseFarms;
    @BindView(R.id.rl_header)
    RelativeLayout mRlHeader;
    @BindView(R.id.tv_facility)
    TextView mTvFacility;
    @BindView(R.id.sf_VideoMonitor)
    SurfaceView sf_VideoMonitor;
    @BindView(R.id.tv_Loading)
    TextView tv_Loading;
    @BindView(R.id.iv_auto)
    ImageView mIvAuto;
    @BindView(R.id.iv_left)
    ImageView mIvLeft;
    @BindView(R.id.iv_up)
    ImageView mIvUp;
    @BindView(R.id.iv_right)
    ImageView mIvRight;
    @BindView(R.id.iv_down)
    ImageView mIvDown;
    @BindView(R.id.tv_focus_sub)
    TextView mTvFousSub;
    @BindView(R.id.tv_focus_plus)
    TextView mTvFocusPlus;
    @BindView(R.id.tv_zoom_sub)
    TextView mTvZoomSub;
    @BindView(R.id.tv_zoom_plus)
    TextView mTvZoomPlus;
    @BindView(R.id.sb_console_speed)
    SeekBar mSbSpeed;

    //站点
    private List<Farms> farmses = new ArrayList<>();
    //站点下区域
    private List<Facility> facilities = new ArrayList<>();
    //区域下设备
    private List<CameraDevices> devices = new ArrayList<>();
    //区域下设备名称集合
    private ArrayList<String> names = new ArrayList<>();

    private CustomPopWindow mListPopWindow;
    private RecyclerView mRvFarms;
    private RecyclerView mRvFacility;
    private FarmsAdapter mFarmsAdapter;
    private FacilityAdapter mFacilityAdapter;

    private View popView;

    //是否更换了站点
    private boolean isChangeFarm;
    //是否更换了区域
    private boolean isChangeFacility;

    //------------------  海康威视相关 ----------------
    public final StartRenderingReceiver receiver = new StartRenderingReceiver();


    /**
     * 正在移动标记
     */
    private boolean isMoving;

    /**
     * 用来判定是否退回了手机桌面，需要重新开始连接播放
     */
    private boolean isNeedConnect;

    /**
     * 返回标记
     */
    private boolean backflag;

    //--------------------------------------------------

    @Override
    protected boolean userDefaultStatus() {
        return true;
    }

    @Override
    protected void initView() {
        mPresenter.getFarms(FrameApp.user.getUsername());
        showProgressDialog();
        //设置用于发广播的上下文
        HC_DVRManager.getInstance().setContext(getContext());
        initHKView();

        initPopView();
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected void onUserVisible() {
        if (isNeedConnect) {
            //设置用于发广播的上下文
            HC_DVRManager.getInstance().setContext(getContext());
            initHKView();
            start();
        }
    }


    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != receiver) {
            getContext().unregisterReceiver(receiver);
        }
        HC_DVRManager.getInstance().stopPlay();
        isNeedConnect = true;
    }

    @Override
    protected void onUserInvisible() {
    }

    @Override
    public void initStatusBar(ImmersionBar immersionBar) {

    }

    @Override
    public int getContentView() {
        return R.layout.fragment_homepage;
    }

    @Override
    protected boolean isApplyEventBus() {
        return true;
    }

    @Override
    protected boolean isApplyButterKnife() {
        return true;
    }

    @Override
    protected void onEventCome(EventCenter eventCenter) {
        if(eventCenter.getEventCode() == Cons.HC_DVRManager.HC_DVR_REPLAY){
            tv_Loading.setText((String)eventCenter.getData());
        }
    }

    @Override
    public void showError(String errorMsg) {
        dismissProgressDialog();
        Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showFarmsSuccess(List<Farms> farms) {
        dismissProgressDialog();
        this.farmses = farms;

        mFarmsAdapter.setList(farms);

        SPUtils.saveFarm(farmses.get(0));
        FrameApp.loadFarm();

        FrameApp.currentFarmId = farmses.get(SPUtils.getInt(Cons.SPCons.FARM_CHOOSE_NUM, 0)).getId();
        mPresenter.getFacilities(farms.get(SPUtils.getInt(Cons.SPCons.FARM_CHOOSE_NUM, 0)).getId());
        showProgressDialog();

        //如果更换了站点，默认更新区域为该站点下第一个
        if (isChangeFarm) {
            SPUtils.putInt(Cons.SPCons.FACILITY_CHOOSE_NUM, 0);
            isChangeFarm = false;
        }
    }

    @Override
    public void showFacilitiesSuccess(List<Facility> facilities) {
        dismissProgressDialog();
        this.facilities = facilities;

        mFacilityAdapter.setList(facilities);

        FrameApp.currentFacilityId = facilities.get(SPUtils.getInt(Cons.SPCons.FACILITY_CHOOSE_NUM, 0)).getId();

        mTvFarms.setText(farmses.get(SPUtils.getInt(Cons.SPCons.FARM_CHOOSE_NUM, 0)).getName() + "/" + facilities.get(SPUtils.getInt(Cons.SPCons.FACILITY_CHOOSE_NUM, 0)).getName());
        mPresenter.getCamera(facilities.get(SPUtils.getInt(Cons.SPCons.FACILITY_CHOOSE_NUM, 0)).getId());
        showProgressDialog();

        //如果更换了区域，通知ObsDevicesFragment更新数据,默认更新设备为该区域下第一个
        //通知设备刷新
        if (isChangeFacility) {
            EventBus.getDefault().post(new EventCenter<>(Cons.Event.EVENT_DEVICEE_DATA));
            SPUtils.putInt(Cons.SPCons.DEVICES_CHOOSE_NUM, 0);

            EventBus.getDefault().post(new EventCenter<>(Cons.Event.EVENT_CONTROL_DEVICES));

            isChangeFacility = false;
        }
    }

    @Override
    public void showCameraSuccess(List<CameraDevices> devices) {
        dismissProgressDialog();
        this.devices = devices;

        FrameApp.currentDevicesId = devices.get(SPUtils.getInt(Cons.SPCons.DEVICES_CHOOSE_NUM, 0)).getId();

        mTvFacility.setText(devices.get(SPUtils.getInt(Cons.SPCons.DEVICES_CHOOSE_NUM, 0)).getName());
        for (int i = 0; i < devices.size(); i++) {
            names.add(devices.get(i).getName().toString());
        }
        start();
    }

    @OnClick({R.id.ll_choose_farms, R.id.tv_show_pic, R.id.rl_video})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_farms:
                showPopListView();
                break;
            case R.id.tv_show_pic:
                Intent mIntent = new Intent(getContext(), CameraPicActivity.class);
                mIntent.putExtra("devices_id", devices.get(SPUtils.getInt(Cons.SPCons.DEVICES_CHOOSE_NUM, 0)).getId());
                startActivity(mIntent);
                break;
            case R.id.rl_video:
                new MultiSelectPopWindow.Builder(getActivity())
                        .setNameArray(names)
                        .setConfirmListener(new MultiSelectPopWindow.OnConfirmClickListener() {
                            @Override
                            public void onClick(int selectNum) {
                                FrameApp.currentDevicesId = devices.get(selectNum).getId();
                                //更换摄像机设备，视频播放
                                mTvFacility.setText(devices.get(selectNum).getName());
                                SPUtils.putInt(Cons.SPCons.DEVICES_CHOOSE_NUM, selectNum);
                                HC_DVRManager.getInstance().stopPlay();
                                start();
                            }
                        })
                        .setCancel(getContext().getResources().getString(R.string.cancel))
                        .setConfirm(getContext().getResources().getString(R.string.sure))
                        .setTitle(getContext().getResources().getString(R.string.devices_select))
                        .build()
                        .show(mIvChooseFarms);

                break;
            default:
                break;
        }
    }

    //站点和区域筛选列表展示
    private void showPopListView() {
        //处理popWindow 显示内容
        mFarmsAdapter.setList(farmses);
        mFacilityAdapter.setList(facilities);
        //创建并显示popWindow
        mListPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(popView)
                .enableBackgroundDark(true)
                .setAnimationStyle(R.style.CustomPopWindowStyle)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(mRlHeader);

        mListPopWindow.setListener(this);

        mIvChooseFarms.setImageResource(R.drawable.btn_up);
    }

    private void initPopView() {
        popView = LayoutInflater.from(getContext()).inflate(R.layout.pop_farms, null);
        GridLayoutManager manager1 = new GridLayoutManager(getContext(), 4);

        mRvFarms = (RecyclerView) popView.findViewById(R.id.rv_famrs);
        mRvFarms.setLayoutManager(manager1);
        mFarmsAdapter = new FarmsAdapter(getContext());
        mRvFarms.setAdapter(mFarmsAdapter);
        mFarmsAdapter.setListener(this);

        mRvFacility = (RecyclerView) popView.findViewById(R.id.rv_facilities);
        GridLayoutManager manager2 = new GridLayoutManager(getContext(), 4);
        mRvFacility.setLayoutManager(manager2);
        mFacilityAdapter = new FacilityAdapter(getContext());
        mRvFacility.setAdapter(mFacilityAdapter);
        mFacilityAdapter.setListener(this);
    }

    /**
     * id:站点id
     */
    @Override
    public void chooseFarms(int id, int position) {
        isChangeFarm = true;
        FrameApp.currentFarmId = id;
        SPUtils.putInt(Cons.SPCons.FARM_CHOOSE_NUM, position);
        //获取站点区域
        mPresenter.getFacilities(id);
        showProgressDialog();
        SPUtils.saveFarm(farmses.get(position));
        FrameApp.loadFarm();
    }

    /**
     * id:站点区域id
     */
    @Override
    public void chooseFacility(int id, int position) {
        mListPopWindow.dissmiss();

        isChangeFacility = true;
        FrameApp.currentFacilityId = id;
        SPUtils.putInt(Cons.SPCons.FACILITY_CHOOSE_NUM, position);
        //获取该区域摄像头设备
        mPresenter.getCamera(facilities.get(SPUtils.getInt(Cons.SPCons.FACILITY_CHOOSE_NUM)).getId());
        showProgressDialog();
    }

    //popwindow dismiss
    @Override
    public void onPopDismiss() {
        mIvChooseFarms.setImageResource(R.drawable.btn_down);
    }


    //以下为海康威视
    private class StartRenderingReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (HC_DVRManager.ACTION_START_RENDERING.equals(intent.getAction())) {
                tv_Loading.setVisibility(View.GONE);
                setSurfaceViewOnClick();
            }
            if (HC_DVRManager.ACTION_DVR_OUTLINE.equals(intent.getAction())) {
                tv_Loading.setText(getString(R.string.tv_connect_cam_error));
            }
        }

    }

    private void setSurfaceViewOnClick() {
        sf_VideoMonitor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        HC_DVRManager.getInstance().stopPlay();
                    }
                }.start();
                startActivity(FullScreenActivity.class);
                backflag = true;
            }
        });
    }


    /**
     * 海康威视相关初始化
     */
    private void initHKView() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        ViewGroup.LayoutParams lp = sf_VideoMonitor.getLayoutParams();
        lp.width = dm.widthPixels;
        lp.height = lp.width / 16 * 9;
        sf_VideoMonitor.setLayoutParams(lp);
        tv_Loading.setLayoutParams(lp);

        sf_VideoMonitor.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                sf_VideoMonitor.destroyDrawingCache();
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            }
        });

        mIvLeft.setOnTouchListener(this);
        mIvUp.setOnTouchListener(this);
        mIvRight.setOnTouchListener(this);
        mIvDown.setOnTouchListener(this);

        mTvFousSub.setOnTouchListener(this);
        mTvFocusPlus.setOnTouchListener(this);
        mTvZoomSub.setOnTouchListener(this);
        mTvZoomPlus.setOnTouchListener(this);

        mIvAuto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                new Thread() {
                    @Override
                    public void run() {
                        if (isMoving) {
                            HC_DVRManager.getInstance().stopMove(5);
                            isMoving = false;
                        } else {
                            HC_DVRManager.getInstance().startMove(5);
                            isMoving = true;
                        }
                    }
                }.start();
            }
        });


        mSbSpeed.setProgress(SPUtils.getInt(Cons.SPCons.CONSOLE_SPEED, 5));
        HC_DVRManager.setSpeed(SPUtils.getInt(Cons.SPCons.CONSOLE_SPEED, 5));
        /**
         * 当前云台速度控制范围为1 - 8
         * */
        mSbSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int speed = seekBar.getProgress() + 1;
                SPUtils.putInt(Cons.SPCons.CONSOLE_SPEED, speed);
                //拖动停止后，更改云台速度
                HC_DVRManager.setSpeed(speed);
            }
        });

    }

    private DeviceBean getDeviceBean(int currentDevicesPos) {
        DeviceBean bean = new DeviceBean();
        if (devices != null && devices.size() != 0) {
            CameraDevices camera = devices.get(currentDevicesPos);
            bean.setIP(camera.getHost());
            bean.setPort(camera.getDataPort() + "");
            bean.setUserName(camera.getUid());
            bean.setPassWord(camera.getPwd());
            bean.setChannel(camera.getChannel() + "");
        }
        return bean;
    }

    private void start() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(HC_DVRManager.ACTION_START_RENDERING);
        filter.addAction(HC_DVRManager.ACTION_DVR_OUTLINE);
        getContext().registerReceiver(receiver, filter);

        tv_Loading.setVisibility(View.VISIBLE);
        tv_Loading.setText(getString(R.string.connecting));
        if (backflag) {
            backflag = false;
            new Thread() {
                @Override
                public void run() {
                    HC_DVRManager.getInstance().setSurfaceHolder(sf_VideoMonitor.getHolder());
                    HC_DVRManager.getInstance().initSDK();
                    HC_DVRManager.getInstance().loginDevice();
                    HC_DVRManager.getInstance().realPlay();
                }
            }.start();
        } else {

            new Thread() {
                @Override
                public void run() {
                    HC_DVRManager.getInstance().setDeviceBean(getDeviceBean(SPUtils.getInt(Cons.SPCons.DEVICES_CHOOSE_NUM, 0)));
                    HC_DVRManager.getInstance().setSurfaceHolder(sf_VideoMonitor.getHolder());
                    HC_DVRManager.getInstance().initSDK();
                    HC_DVRManager.getInstance().loginDevice();
                    HC_DVRManager.getInstance().realPlay();
                }
            }.start();
        }
        isNeedConnect = false;
    }

    @Override
    public boolean onTouch(final View v, final MotionEvent event) {
        if (isMoving) {
            return true;
        }

        new Thread() {
            @Override
            public void run() {
                switch (v.getId()) {
                    case R.id.iv_up:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startMove(8);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopMove(8);
                        }
                        break;
                    case R.id.iv_left:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startMove(4);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopMove(4);
                        }
                        break;
                    case R.id.iv_right:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startMove(6);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopMove(6);
                        }
                        break;
                    case R.id.iv_down:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startMove(2);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopMove(2);
                        }
                        break;
                    case R.id.tv_focus_sub:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startFocus(-1);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopFocus(-1);
                        }
                        break;
                    case R.id.tv_focus_plus:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startFocus(1);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopFocus(1);
                        }
                        break;
                    case R.id.tv_zoom_sub:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startZoom(-1);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopZoom(-1);
                        }
                        break;
                    case R.id.tv_zoom_plus:
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            VibrateHelp.vSimple(getContext(), 100);
                            HC_DVRManager.getInstance().startZoom(1);
                        }
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            HC_DVRManager.getInstance().stopZoom(1);
                        }
                        break;
                    default:
                        break;
                }
            }
        }.start();

        return true;
    }

}
